#! /usr/bin/env python

# CONFIGURATION EXAMPLE
#address = '00:0A:3A:2A:EC:03'
#port = 1

from gpggaparser import *
from lightblue import *

s = socket()

try:
	if address and port:
		print "Connecting with predefined device:", address, "on port", port
except NameError:
	# address and/or port is not set
	(address, port, xxx) = selectservice()
	print "Connecting with device:", address, "on port", port

s.connect((address, port))

data = ""
olddata = ""

while True:
	data = s.recv(1024)

	if len(data) > 0:
		data = olddata + data
		# split the data into a list of lines, but make sure we preserve the end of line information.
		lines = data.splitlines(1)

		# iterate over each line
		for line in lines:	

			# if the line has a carriage return and a linefeed, we know we have a complete line so we can remove those characters and print it.
			if line.find("\r\n") != -1 :
				line = line.strip()
				print line
				gpsstring = line.split(',')

				if gpsstring[0] == '$GPGGA' :
					gpgga = GPGGAParser(line)

					fileHandle = open ( '/tmp/gps', 'w' )
					fileHandle.write ( repr(gpgga.latitude) )
					fileHandle.write ( "\n" )
					fileHandle.write ( repr(gpgga.longitude) )
					fileHandle.close()
				
				# empty the olddata variable now we have used the data.
				olddata = ""
			
			# else we need to keep the line to add to data
			else :
				olddata = line
